
//自定义Promise函数模块：IIFE

(function (window){

    function Promise(excutor){
        this.status = 'pending'
        this.data = undefined
        this.callbacks = [] //每个元素结构：{onResolved(){},onRejected(){}}

        resolve = (value) => {
            if(this.status !== 'pending'){
                return
            }
            this.status = "resolved"
            this.data = value
            //如果有待执行的callback函数，立即异步执行回调函数onResolved
            if(this.callbacks.length > 0){
                //放入队列执行所有成功的回调
                setTimeout(() => {
                    this.callbacks.forEach(callbacksObj => {
                        callbacksObj.onResolved(value)
                    })
                },0)
            }
        }

        reject = (reason) => {
            if(this.status !== 'pending'){
                return
            }
            this.status = "rejected"
            this.data = reason
            //如果有待执行的callback函数，立即异步执行回调函数onRejected
            if(this.callbacks.length > 0){
                //放入队列执行所有成功的回调
                setTimeout(() => {
                    this.callbacks.forEach(callbacksObj => {
                        callbacksObj.onRejected(reason)
                    })
                },0)
            }
        }
        //执行器抛异常，则promise变为rejected。
        try{
            excutor(resolve, reject)
        } catch (err){
            console.log(1111);
            reject(err)
        }
    }

    Promise.prototype.then = function (onResolved, onRejected){
        //如果当前还是pending状态，则将回调函数保存起来
        this.callbacks.push({
            onResolved,
            onRejected
        })
    }

    Promise.prototype.catch = function (onRejected){

    }

    Promise.resolve = function (value){

    }

    Promise.reject = function (reason){
        
    }

    Promise.all = function (promises){

    }

    Promise.race = function (promises){

    }

    window.Promise = Promise
})(window)